<template>
  <div class="setting-wrapper">
    <el-tabs v-model="activeSetting" class="pt-24" @tab-click="tabClick">
      <el-tab-pane label="组件设置" name="widgetSetting">
        <el-form
          v-if="isNotEmpty(componentData)"
          ref="widgetForm"
          :model="{ componentData }"
          label-width="106px"
          :show-message="false"
          @validate="onValidateWidgetSetting"
        >
          <el-collapse v-model="widgetSettingCollapse" class="theme" style="position: relative">
            <el-collapse-item v-for="(item, i) in componentData" :key="item.id" :name="item.id">
              <!-- 编辑组件标题 -->
              <template #title>
                <div @click.stop>
                  <div v-if="editLabelId === item.id" class="d-flex al-center">
                    <el-input
                      v-model.trim="item.label"
                      :data-label="item.id"
                      class="label-input"
                      maxlength="20"
                      @blur="onLabelInputBlur"
                    >
                      <template #suffix><SvgIcon icon-class="edit-pencil" class="mr-12 t-theme"></SvgIcon></template>
                    </el-input>
                  </div>
                  <div v-else class="label d-flex al-center">
                    <span>{{ item.label }}</span>
                    <SvgIcon
                      icon-class="edit-pencil"
                      class="ml-8"
                      style="color: #cecece"
                      @click.stop="onEditLabel(item)"
                    ></SvgIcon>
                  </div>
                </div>
              </template>
              <!-- 组件setting -->
              <component
                :is="settings[item.component]"
                :key="item.id"
                v-model="componentData[i]"
                :index="i"
                @click.native.self="onClickSettingItem(i)"
              ></component>
            </el-collapse-item>
          </el-collapse>
        </el-form>
        <div v-else class="empty fs-md t-center">
          <div>画布中尚未存在组件</div>
          <div>将左侧组件拖拽进入画布即可编辑组件属性</div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="页面设置" name="pageSetting">
        <el-form ref="pageForm" :model="pageConfig" label-width="106px" :hide-required-asterisk="true">
          <el-collapse v-model="pageSettingCollapse" class="theme">
            <!-- <el-collapse-item title="作品名称">
              <div class="form-group pr-64">
                <el-form-item label="作品名称" prop="appNAme" class="d-flex">
                  <el-input
                  ></el-input>
                </el-form-item>
              </div>
            </el-collapse-item> -->
            <el-collapse-item title="作品尺寸" name="size-setting">
              <div class="form-group pr-64">
                <el-form-item label="当前尺寸" label-width="94px">
                  <el-select v-model="mode" class="size-selector" :disabled="true">
                    <el-option value="h5" :label="`750*${previewer.height}/ 长页`"></el-option>
                    <el-option value="poster" label="210*297mm/A4一页通"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-collapse-item>
            <el-collapse-item title="背景填充" name="fill-setting">
              <BackgroundSetting v-model="pageConfig.pageStyle" />
            </el-collapse-item>
            <el-collapse-item v-if="isH5" title="翻页设置" name="turn-setting">
              <PageTurnSetting v-model="pageConfig.pageTurn"
            /></el-collapse-item>
          </el-collapse>
        </el-form>
      </el-tab-pane>

    </el-tabs>
  </div>
</template>

<script>
  import { mapGetters, mapMutations } from 'vuex';
  import { notEmptyRules, isNotEmpty } from '@/utils';
  import PictureMaterialSelector from '@/components/PictureMaterialSelector';
  import ColorSetting from '../settingComponent/ColorSetting';
  import BackgroundSetting from '../settingComponent/BackgroundSetting';
  import PageTurnSetting from '../settingComponent/PageTurnSetting';
  import ChannelSetting from '../settingComponent/ChannelSetting';
  import ShareTipSetting from '../settingComponent/ShareTipSetting';
  import Group from './Group/Setting';
  import { Basic, H5 } from '../landingPageWidget/index';

  export default {
    components: {
      PictureMaterialSelector,
      ColorSetting,
      BackgroundSetting,
      PageTurnSetting,
      ChannelSetting,
      ShareTipSetting
    },

    inject: ['isH5'],

    props: {
      pageConfig: { type: Object, default: () => ({}) },
      applyConfig: { type: Object, default: () => ({}) }
    },

    data() {
      return {
        notEmptyRules,
        activeSetting: 'widgetSetting', // 默认激活tab
        editLabelId: '', // 当前编辑组件label的widget.id
        channelList: [],
        widgetSettingValidating: false, // 校验组件配置中
        validating: false
      };
    },

    computed: {
      ...mapGetters('component', ['componentData', 'activeComponent', 'activeComponentIndex', 'previewer']),
      pageSettingCollapse: {
        set: (arr) => arr,
        get: () => ['size-setting', 'fill-setting', 'turn-setting']
      },
      widgetSettingCollapse: {
        set: (arr) => arr,
        get() {
          return this.componentData.map((item) => item.id);
        }
      },
      showShareSetting() {
        return this.applyConfig?.channelCodes.some((channelCode) =>
          this.channelList.some((channel) => channel.channelCode === channelCode && channel.type === 1)
        );
      },
      settings() {
        return { ...Basic.settings, ...H5.settings, Group };
      },
      mode() {
        return 'h5';
      }
    },

    watch: {
      activeComponent(newValue, oldValue) {
        if (newValue === oldValue) return;
        this.scrollToActive(this.activeComponentIndex, this.activeComponentIndex === undefined);
      }
    },

    mounted() {
      this.$EventBus.$on('hook:ChangeSettingPanel', (val) => {
        this.activeSetting = val;
      });
    },

    beforeDestroy() {
      this.$EventBus.$off('hook:ActiveComponent');
      this.$EventBus.$off('hook:ChangeSettingPanel');
    },

    methods: {
      ...mapMutations('component', ['ACTIVE_COMPONENT', 'DEPRESS_COMPONENT']),
      isNotEmpty,

      tabClick() {
        this.$nextTick(() => {
          if (this.activeSetting === 'widgetSetting') {
            this.scrollToActive(this.activeComponentIndex, true);
          } else {
            document.querySelector('.setting-wrapper .el-tabs__content').scrollTop = 0;
          }
        });
      },
      // 聚焦/失焦作品名称
      onFocusAppName() {
        this.DEPRESS_COMPONENT();
        this.$EventBus.$emit('hook:editAppName', true);
      },
      onBlurAppName() {
        this.$EventBus.$emit('hook:editAppName', false);
      },
      // 点击组件配置项
      onClickSettingItem(i) {
        this.ACTIVE_COMPONENT(i);
      },

      // 校验所有配置表单
      async validConfig() {
        this.validating = true;
        let isValid = true;

        if (!this.$refs.widgetForm) {
          this.$message.error('请先添加组件');
          this.activeSetting = 'widgetSetting';
          this.validating = false;
          return false;
        }

        const componentLabelList = this.componentData.map((component) => component.label);
        const componentLabelSet = new Set(componentLabelList);
        if (componentLabelList.length !== Array.from(componentLabelSet).length) {
          this.$message.error('组件名称不可重复');
          this.activeSetting = 'widgetSetting';
          this.validating = false;
          return false;
        }

        isValid = await this.$refs.widgetForm.validate();
        if (isValid === false) {
          this.validating = false;
          return isValid;
        }

        isValid = await this.$refs.pageForm.validate();
        if (isValid === false) {
          this.validating = false;
          return isValid;
        }

        isValid = await this.$refs.applyForm.validate();
        if (isValid === false) {
          this.validating = false;
          return isValid;
        }

        return isValid;
      },

      // 监听：校验组件配置表单
      onValidateWidgetSetting(prop, isValid, message) {
        if (!this.validating) return;
        if (isValid) return;
        message = message instanceof Error ? '请检查组件配置' : message;
        this.$message.error(message);
        // 滚动至对应组件
        this.activeSetting = 'widgetSetting';
        const matcher = /^componentData\.(\d+)\./.exec(prop);
        this.scrollToActive(Number(matcher[1]), true);
        this.validating = false;
      },

      // 监听：校验作品设置表单
      onValidateApplySetting(prop, isValid, message) {
        if (!this.validating) return;
        if (isValid) return;
        message = message instanceof Error ? '请检查作品设置' : message;
        this.$message.error(message);
        this.activeSetting = 'applySetting';
        this.validating = false;
      },

      // 自动激活tab并滚动
      scrollToActive(activeIndex, hasInWidgetSetting = false) {
        if (activeIndex === undefined) {
          const collapseItems = document.querySelectorAll('#pane-widgetSetting .el-collapse-item');
          collapseItems.forEach((item) => item.removeAttribute('state'));

          if (hasInWidgetSetting) return;
        }
        this.activeSetting = 'widgetSetting';
        this.$nextTick(() => {
          const $scroller = document.querySelector('.setting-wrapper .el-tabs__content');
          const collapseItems = document.querySelectorAll('#pane-widgetSetting .el-collapse-item');
          collapseItems.forEach((item) => item.removeAttribute('state'));
          const activeCollapseItem = collapseItems[activeIndex];
          const top = activeCollapseItem.offsetTop;
          collapseItems.forEach((item) => item.removeAttribute('state'));
          activeCollapseItem.setAttribute('state', 'shadow');
          if ($scroller.scrollTo) {
            $scroller.scrollTo({ top, behavior: 'smooth' });
          } else {
            $scroller.scrollTop = top;
          }
        });
      },

      // 编辑组件标签时
      onEditLabel(item) {
        this.editLabelId = item.id;
        this.editLabelName = item.label;
        this.$nextTick(() => document.querySelector(`input[data-label='${item.id}']`).focus());
      },

      // 编辑组件标签完成时
      onLabelInputBlur() {
        const editComponent = this.componentData.find((component) => component.id === this.editLabelId);
        const hasSameName = this.componentData.some(
          (widget) => widget.label === editComponent.label && widget.id !== editComponent.id
        );
        if (hasSameName) {
          this.$message.error('组件名称不可重复！');
          document.querySelector(`input[data-label='${this.editLabelId}']`).focus();
          return;
        } else {
          this.editLabelId = '';
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .setting-wrapper {
    border-left: 1px solid map-get($bdColors, 'grey');
    // width: 558px;
    width: 560px;
    min-height: 100%;

    ::v-deep > .el-tabs .el-tabs__nav {
      display: flex;
      width: 100%;

      .el-tabs__item {
        flex: 1;
      }
    }
  }

  #pane-pageSetting,
  #pane-widgetSetting {
    margin-top: -16px;
  }

  // 无组件状态
  .empty {
    line-height: 1.5;
    color: #cecece;
    user-select: none;
  }

  // 配置表单组
  ::v-deep .form-group {
    border-radius: 6px;
    padding: 24px;
    background-color: map-get($bgColors, 'lightgrey');

    &:not(:last-child) {
      margin-bottom: 24px;
    }

    .group-item:not(:last-of-type) {
      margin-bottom: 24px;
    }
  }

  .bd-filt-6 {
    border-radius: 6px;
  }

  // 组件标题编辑input
  .label-input.el-input {
    width: 217px;

    ::v-deep .el-input__inner {
      border-color: map-get($bdColors, 'theme') !important;
      padding: 0 30px 0 16px;
      font-weight: bold;
    }

    ::v-deep .el-input__suffix {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .label {
    font-size: 14px;
  }

  // 按钮配置区域
  ::v-deep .button-box {
    .el-input {
      width: 168px;
    }
  }

  // 覆盖样式
  ::v-deep {
    .el-form--inline .el-form-item {
      margin-right: 0;
    }

    .el-form-item__label {
      user-select: none;
    }

    .el-form-item__content {
      flex: 1;
    }

    .el-select,
    .el-input-number {
      width: 100%;
    }

    .el-input-number--small {
      width: 80px;
    }

    .el-radio-button {
      &:first-child .el-radio-button__inner {
        border-radius: 2px 0 0 2px;
      }

      &:last-child .el-radio-button__inner {
        border-radius: 0 2px 2px 0;
      }

      .el-radio-button__inner {
        padding: 8px 14px;
        font-size: 14px;

        .el-input {
          max-width: 75px;
          font-size: 14px;

          .el-input__inner {
            border: none;
            border-radius: 0;
            padding: 0;
            height: 14px;
            line-height: 1;
            text-align: center;
            color: #999;
          }
        }
      }

      .el-icon-error {
        color: #cecece;
      }

      &.is-active .el-icon-error,
      & .el-radio-button__inner:hover .el-icon-error {
        color: map-get($colors, 'theme');
        transition: all 0.3s;
      }
    }

    .el-collapse {
      .el-collapse-item {
        margin: 0 -16px 16px;
        border-radius: 4px;
        padding: 0 16px;

        &[state='shadow'] {
          box-shadow: 0 2px 12px 0 rgba(13, 121, 244, 0.5);
          transition: box-shadow 0.2s;
        }

        .el-collapse-item__header {
          padding: 16px 0;
        }

        .el-collapse-item__wrap {
          border-bottom: none;

          .el-collapse-item__content {
            padding: 16px 0;
          }
        }
      }
    }

    .el-tabs {
      // padding-top: 25px;
      > .el-tabs__header .el-tabs__item {
        width: 183px;
      }
    }

    .el-date-editor--daterange.el-input__inner {
      width: 100%;
    }
  }
  // @media screen and (max-width: 1440px) {
  //   .setting-wrapper {
  //     width: 38%;
  //   }
  // }
</style>
